<script setup lang="ts">
    import {
        Management,
        Promotion,
        Avatar,
        School,
        Notebook,
        Tickets,
        User,
        Crop,
        EditPen,
        SwitchButton,
        CaretBottom,
    } from '@element-plus/icons-vue'
    import axios from 'axios';
    import {
        useRouter
    } from 'vue-router';
    import {
        ref,
        onMounted
    } from 'vue';
    import {
        ElMessage
    } from 'element-plus';
    import {
        AdminUpdateService,
        UpdatePasswordService,
        adminLoginService
    } from '@/api/admin.js'
import { List } from 'echarts';
    const router = useRouter();
    const jwtToken = localStorage.getItem('adminJwtToken');
    // 设置请求头部，包含jwt令牌
    const config = {
        headers: {
            Authorization: `Bearer ${jwtToken}`
        }
    };

    const adminModel = ref({
        adminId: '',
        adminName: '',
        adminPassword: '',
        adminPhoto: '',
        adminPhone:''
    });

    const fetchData = async () => {
        try {
            const response = await axios.get('http://localhost:9090/admin/jwt', config);
            const adminData = response.data.data.admin;
            if (adminData) {
                adminModel.value.adminId = adminData.adminId;
                adminModel.value.adminName = adminData.adminName;
                adminModel.value.adminPassword = adminData.adminPassword;
                adminModel.value.adminPhone=adminData.adminPhone
                adminModel.value.adminPhoto = adminData.adminPhoto;
            } else {
                console.error('User data not found in the response');
            }
        } catch (error) {
            console.log(error);
        }
    };

    onMounted(() => {
        fetchData();
    });
    const dialogVisible = ref(false)
    const avatarVisible = ref(false)

    const logout = () => {
        //清除用户的JWT令牌
        clearJWtToken();
        //重定向到登录页面
        router.push('/');
    };

    const clearJWtToken = () => {
        localStorage.removeItem('adminJwtToken');
    };
    const tempImg=ref();
    const uploadRef = ref()
    const updateImg = async () => {
        try {
            adminModel.value.adminPhoto=tempImg.value;
            let result = await AdminUpdateService(adminModel.value);
            if(result.code===1){
                ElMessage.success('修改成功');
                const response=await adminLoginService(adminModel.value);
                if(response.code===1){
                    localStorage.setItem('jwtToken', response.data);
                }
                adminModel.value.adminPhoto=tempImg.value;
                uploadRef.value.clearFiles();
                avatarVisible.value = false;
            }else{
                ElMessage.error(result.msg);
            }
        } catch (error) {
            ElMessage.error('修改失败');
        }
    }

    const registerData = ref({
        adminPassword: '',
        repassword: ''
    });
    const passwordVisible = ref(false);
    const temp = ref();
    //校验密码的函数
    const checkRePassword = async () => {
        if (registerData.value.adminPassword === '') {
            ElMessage.error("请输入密码")
        } else if (registerData.value.adminPassword !== registerData.value.repassword) {
            ElMessage.error('两次输入的密码不一致')
        } else {
            temp.value = adminModel.value.adminPassword;
            adminModel.value.adminPassword = registerData.value.adminPassword;
            const result = await UpdatePasswordService(adminModel.value);
            if (result.code === 1) {
                ElMessage.success('修改密码成功');
                localStorage.removeItem('adminUserName');
                localStorage.removeItem('adminPassword');
                passwordVisible.value = false;
                clearPassData();
                temp.value = "";
            } else {
                ElMessage.error('修改密码失败');
                adminModel.value.adminPassword = temp.value;
            }
        }
    }

    const clearPassData = () => {
        registerData.value = {
            adminPassword: '',
            repassword: ''
        };
    }

    const handleSuccess=async(response)=>{
        tempImg.value=response.data;
    }

    const showDateForm=async()=>{
        avatarVisible.value=true;
        tempImg.value = adminModel.value.adminPhoto;
    }
</script>

<template>
    <el-container class="layout-container">
        <!-- 左侧菜单 -->
        <el-aside width="200px">
            <div class="el-aside__logo"></div>
            <!-- element-plus的菜单标签 -->
            <div style="width: 200px;height: 60px;margin: 0 auto;color: aliceblue;margin-left: 30px;margin-top: 40px;">
                <span style="font-size: 18px;"><b>
                学生管理系统</b></span>
            </div>
            <el-menu active-text-color="#ffd04b" background-color="#232323" text-color="#fff" router>
                <el-menu-item index="/bi">
                    <el-icon>
                        <Management />
                    </el-icon>
                    <span>BI图</span>
                </el-menu-item>
                <el-menu-item index="/profession">
                    <el-icon>
                        <Management />
                    </el-icon>
                    <span>专业管理</span>
                </el-menu-item>
                <el-menu-item index="/teacher">
                    <el-icon>
                        <Avatar />
                    </el-icon>
                    <span>教师管理</span>
                </el-menu-item>
                <el-menu-item index="/mainclass">
                    <el-icon>
                        <School />
                    </el-icon>
                    <span>班级管理</span>
                </el-menu-item>
                <el-menu-item index="/course">
                    <el-icon>
                        <Notebook />
                    </el-icon>
                    <span>课程管理</span>
                </el-menu-item>
                <el-menu-item index="/student">
                    <el-icon>
                        <Promotion />
                    </el-icon>
                    <span>学生管理</span>
                </el-menu-item>
                <el-menu-item index="/exam">
                    <el-icon>
                        <Tickets />
                    </el-icon>
                    <span>成绩管理</span>
                </el-menu-item>
            </el-menu>
        </el-aside>
        <!-- 右侧主区域 -->
        <el-container>
            <!-- 头部区域 -->
            <el-header>
                <div><strong>{{ adminModel.adminName }}</strong></div>
                <el-dropdown placement="bottom-end">
                    <span class="el-dropdown__box">
                        <el-avatar :src="adminModel.adminPhoto" />
                        <el-icon>
                            <CaretBottom />
                        </el-icon>
                    </span>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item command="profile" :icon="User" @click="dialogVisible=true">基本资料
                            </el-dropdown-item>
                            <el-dropdown-item command="avatar" :icon="Crop" @click="showDateForm()">修改信息
                            </el-dropdown-item>
                            <el-dropdown-item command="password" :icon="EditPen" @click="passwordVisible=true">重置密码
                            </el-dropdown-item>
                            <el-dropdown-item command="logout" :icon="SwitchButton" @click="logout">退出登录
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </el-header>
            <!-- 信息弹窗 -->
            <el-dialog v-model="dialogVisible" width="30%" :top="'calc(200px)'">
                <el-form :model="adminModel" label-width="100px" style="padding-right: 30px">
                    <el-form-item label="姓名:" prop="adminName">
                        {{ adminModel.adminName }}
                    </el-form-item>
                    <el-form-item label="密码:" prop="adminPassword">
                        {{ adminModel.adminPassword }}
                    </el-form-item>
                    <el-form-item label="手机:" prop="adminPhone">
                        {{ adminModel.adminPhone }}
                    </el-form-item>
                    <el-form-item label="照片:" prop="adminImg">
                        <div class="photo-cell">
                            <img v-if="adminModel.adminPhoto" :src="adminModel.adminPhoto" alt="Photo">
                            <img v-else src="@/assets/bap.png"/>
                        </div>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="dialogVisible = false" type="primary">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 修改弹窗 -->
            <el-dialog v-model="avatarVisible" width="30%">
                <el-form :model="adminModel" label-width="100px" style="padding-right: 30px">
                    <el-form-item label="手机" prop="adminPhone">
                        <el-input v-model="adminModel.adminPhone" minlength="1"></el-input>
                    </el-form-item>
                    <el-form-item label="头像" prop="adminPhoto">
                        <el-upload
                            ref="uploadRef"
                            class="upload-demo"
                            action="http://localhost:9090/upload"
                            :limit="1"
                            :on-success="handleSuccess"
                        >
                            <el-button type="success">select file</el-button>
                        </el-upload>
                    </el-form-item>
                    <span style="margin-left: 350px;">
                        <el-button @click="avatarVisible = false ;updateImg()" type="primary">确定</el-button>
                    </span>
                </el-form>
            </el-dialog>

            <!-- 密码弹窗 -->
            <el-dialog v-model="passwordVisible" width="30%" :top="'calc(200px)'">
                <el-form :model="registerData" label-width="100px" style="padding-right: 30px">
                    <el-form-item prop="adminPassword" label="输入密码">
                        <el-input type="password" placeholder="请输入密码" v-model="registerData.adminPassword"></el-input>
                    </el-form-item>
                    <el-form-item prop="repassword" label="重复密码">
                        <el-input type="password" placeholder="请输入再次密码" v-model="registerData.repassword"></el-input>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="checkRePassword" type="primary">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 中间区域 -->
            <el-main>
                <router-view></router-view>
            </el-main>
            <!-- 底部区域 -->
            <el-footer>学生管理系统 ©2024 Created by Sun</el-footer>
        </el-container>
    </el-container>
</template>

<style lang="scss" scoped>
    .layout-container {
        height: 100vh;

        .el-aside {
            background-color: #232323;


            .el-menu {
                border-right: none;
            }
        }

        .el-header {
            background-color: #fff;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .el-dropdown__box {
                display: flex;
                align-items: center;

                .el-icon {
                    color: #999;
                    margin-left: 10px;
                }

                &:active,
                &:focus {
                    outline: none;
                }
            }
        }

        .el-footer {
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 14px;
            color: #666;
        }
    }

    .photo-cell {
        width: 80px;
        height: 80px;
    }

    .photo-cell img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .el-image {
        padding: 0 5px;
        max-width: 300px;
        max-height: 200px;
        width: 100%;
        height: 200px;
    }

    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 100%;
        background: var(--el-fill-color-light);
        color: var(--el-text-color-secondary);
        font-size: 30px;
    }
</style>